package pers.xiaojun.boot.jackson.config;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import pers.xiaojun.boot.common.util.JsonUtils;
import pers.xiaojun.boot.jackson.deser.TimestampLocalDateTimeDeserializer;
import pers.xiaojun.boot.jackson.ser.TimestampLocalDateTimeSerializer;

import java.time.*;
import java.util.List;

/**
 * jackson 配置
 *
 * @author xiaojun
 * @since 2025-10-08
 */
@AutoConfiguration
public class JacksonAutoConfiguration {

    /**
     * 统一配置 SpringBoot 中所有的 ObjectMapper
     *
     * @param objectMappers 对象映射
     * @return {@link JsonUtils}
     */
    @Bean
    public JsonUtils jsonUtils(List<ObjectMapper> objectMappers) {
        SimpleModule simpleModule = new SimpleModule();
        simpleModule
                .addSerializer(LocalDate.class, LocalDateSerializer.INSTANCE)
                .addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE)
                .addSerializer(LocalTime.class, LocalTimeSerializer.INSTANCE)
                .addDeserializer(LocalTime.class, LocalTimeDeserializer.INSTANCE)
                // 新增 LocalDateTime 序列化、反序列化规则，使用 Long 时间戳
                .addSerializer(LocalDateTime.class, TimestampLocalDateTimeSerializer.INSTANCE)
                .addDeserializer(LocalDateTime.class, TimestampLocalDateTimeDeserializer.INSTANCE);

        // 为每个 ObjectMapper 注册 SimpleModule
        objectMappers.forEach(om -> om.registerModule(simpleModule));

        // 更新 JsonUtils 中的 ObjectMapper
        JsonUtils.setObjectMapper(CollUtil.getFirst(objectMappers));

        return new JsonUtils();
    }

}
